<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>PDF 查看</title>

  <!-- uni 的 SDK -->
  <script src="https://unpkg.com/@dcloudio/uni-webview-js@0.0.3/index.js"></script>

  <!-- ✅ 使用 jsDelivr CDN（更稳定，避免语法错误） -->
  <script src="/js_sdk/pdf/pdf.min.js"></script>

  <style>
    body {
      font-family: Arial, sans-serif;
      text-align: center;
      margin: 0;
      padding: 20px;
      background-color: #f5f5f5;
    }

    #pdf-container {
      margin: 20px auto;
      max-width: 800px;
      border: 1px solid #ddd;
      border-radius: 8px;
      overflow: hidden;
      background-color: white;
      box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    }

    .page-container {
      margin: 20px 0;
      page-break-inside: avoid;
    }

    .page-info {
      font-size: 14px;
      color: #666;
      margin-bottom: 8px;
    }

    canvas {
      width: 100%;
      height: auto;
      display: block;
      image-rendering: -moz-crisp-edges;
      image-rendering: pixelated;
      border-radius: 4px;
    }

    .error-message {
      color: red;
      padding: 30px;
      font-size: 16px;
    }
  </style>
</head>

<body>
  <h2>PDF 预览</h2>
  <div id="pdf-container">
    <p>加载中，请稍候...</p>
  </div>

  <script>
    // ✅ 立即设置 workerSrc（必须在加载后立刻设置）
    window.pdfjsLib = window.pdfjsLib || {};
    pdfjsLib.GlobalWorkerOptions.workerSrc = '/js_sdk/pdf/pdf.worker.min.js';

    // ✅ DOM 加载完成后开始渲染
    document.addEventListener('DOMContentLoaded', async () => {
      const container = document.getElementById('pdf-container');
      const url = '/doc/demo.pdf'; // 你的本地 PDF 路径

      try {
        console.log('开始加载 PDF:', url);
        container.innerHTML = '<p>正在加载 PDF...</p>';

        // 1. 加载 PDF
        const loadingTask = pdfjsLib.getDocument(url);
        const pdf = await loadingTask.promise;
        console.log(`✅ PDF 加载成功，共 ${pdf.numPages} 页`);

        // 清空容器
        container.innerHTML = '';

        const scale = 2.0; // 渲染清晰度

        // 2. 遍历每一页并渲染
        for (let pageNum = 1; pageNum <= pdf.numPages; pageNum++) {
          const page = await pdf.getPage(pageNum);
          const viewport = page.getViewport({ scale });

          // 创建页面容器
          const pageContainer = document.createElement('div');
          pageContainer.className = 'page-container';

          // 添加页码提示
          const pageInfo = document.createElement('div');
          pageInfo.className = 'page-info';
          pageInfo.textContent = `第 ${pageNum} 页（共 ${pdf.numPages} 页）`;
          pageContainer.appendChild(pageInfo);

          // 创建 canvas
          const canvas = document.createElement('canvas');
          const ctx = canvas.getContext('2d');
          canvas.height = viewport.height;
          canvas.width = viewport.width;

          pageContainer.appendChild(canvas);
          container.appendChild(pageContainer);

          // 渲染页面
          await page.render({
            canvasContext: ctx,
            viewport: viewport
          }).promise;

          console.log(`✅ 第 ${pageNum} 页渲染完成`);
        }

        console.log('🎉 所有页面渲染完成！');
      } catch (error) {
        console.error('❌ PDF 加载失败:', error);
        container.innerHTML = `
          <div class="error-message">
            <p><strong>加载失败</strong></p>
            <p>${error.message}</p>
            <p style="font-size:12px;color:#999;">请检查 PDF 路径是否正确，或网络是否正常</p>
          </div>
        `;
      }
    });

    // ✅ uni 相关逻辑
    document.addEventListener('UniAppJSBridgeReady', function () {
      console.log('UniApp JSBridge Ready');
      uni.postMessage({
        data: { action: 'message' }
      });
    });
  </script>
</body>

</html>